package com.woyao;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.MemberSummary;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

/**
 * Created by Administrator on 2016/9/19 0019.
 */

public class MemberAdapter extends RecyclerView.Adapter<MemberAdapter.ViewHolder>
{

    private LayoutInflater mInflater;

    private List<MemberSummary> thedata = new ArrayList<MemberSummary>();
    private Changed onChanged;

    private String Selection = null ;
    Context thecontext;

    public MemberAdapter(Context context, List<MemberSummary> data ) {
        thecontext = context;
        this.mInflater = LayoutInflater.from(context);

        thedata= data;

    }


    public interface Changed{
        void view(MemberSummary ms);
    }
    public void setChangedHandler(Changed changed){
        this.onChanged = changed;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= mInflater.inflate(R.layout.member_item,parent,false);
        //view.setBackgroundColor(Color.RED);
        ViewHolder viewHolder=new ViewHolder(view);
        return viewHolder;
    }

    /**
     * 数据的绑定显示
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final MemberSummary curData =  thedata.get(position);

        if (curData.getStatus().equals("recommend")){
            holder.applyBtn.setVisibility(View.VISIBLE);
        }else{
            holder.applyBtn.setVisibility(View.GONE);
        }

        holder.theOrder.setText(  (position +1) +"") ;


        holder.theTitle.setText( curData.getTitle() );

        if ( !curData.getStatus().equals("ongoing") ) {
            holder.theTitle.setTextColor(ContextCompat.getColor(thecontext, R.color.colorSubTitleText));
        }else{
            holder.theTitle.setTextColor(ContextCompat.getColor(thecontext, R.color.colorTextDarkGrey));

        }

        holder.theSubtitle.setText( curData.getDescription() );

        if (curData.getMessage_num() >0 ) {
            holder.theMsg.setText(curData.getMessage_num() + "");
        }else{
            holder.theMsg.setVisibility(View.INVISIBLE);
        }

        holder.theImage.setImageResource(R.drawable.no_avartar);
        if (StringUtil.notNullOrEmpty(curData.getSnailview())) {
            Picasso.with(thecontext)
                    .load(curData.getSnailview())
                    .into(holder.theImage);
        }
        holder.theContent.setOnClickListener( new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                MemberSummary curdata = thedata.get(holder.getAdapterPosition());
                curData.setMessage_num(0);
                holder.theMsg.setVisibility(View.INVISIBLE);
                onChanged.view(curdata  );
            }
        });

        holder.applyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final  MemberSummary curdata = thedata.get(holder.getAdapterPosition());
                final Button theBtn = ( Button)view;

                Dialog alertDialog = new AlertDialog.Builder(thecontext).
                        setTitle("提示").
                        setMessage("申请加入吗？").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                applyOrg( curdata.getOrg_id());
                                theBtn.setEnabled(false);
                                theBtn.setText("已申请");
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).
                        create();
                alertDialog.show();

            }
        });

    }

    @Override
    public int getItemCount() {
        return thedata.size();
    }

    //自定义的ViewHolder，持有每个Item的的所有界面元素
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView theTitle;
        public TextView theSubtitle;
        public LinearLayout theContent;
        public CircleImageView theImage;
        public Button theMsg;
        public Button applyBtn;
        public TextView theOrder;

        public ViewHolder(View view) {
            super(view);


            theTitle = (TextView) view.findViewById(R.id.chance_title);
            theSubtitle = (TextView) view.findViewById(R.id.chance_subtext);
            theContent = (LinearLayout) view.findViewById(R.id.chance_content);
            theImage = (CircleImageView) view.findViewById(R.id.chance_image);
            theMsg  = (Button)  view.findViewById(R.id.chance_msg);
            applyBtn  = (Button)  view.findViewById(R.id.id_apply_org);
            theOrder  = (TextView)  view.findViewById(R.id.chance_order);
        }

    }

    private  void applyOrg( final Integer orgid){


        AsyncTask<Void,Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<BaseResponse> responseCall = svc.applyOrg(userId,orgid);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        if ( response.isSuccess()){
                            Common.alert(thecontext,response.getMessage());
                        }else{
                            Dialog alertDialog = new AlertDialog.Builder(thecontext).
                                    setTitle("信息").
                                    setMessage(response.getMessage()).
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (response.getCondition()) {
                                                case "verify":
                                                    renderVerify();
                                                    break;
                                                case "charge":
                                                    renderMoney();
                                                    break;

                                                default:
                                            }
                                        }
                                    }).
                                    setPositiveButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).
                                    create();
                            alertDialog.show();
                        }
                    }
                    @Override
                    protected void onCancelled() {
                    }
                };
        task.execute();

    }
    private void renderMoney( ){
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(thecontext, MoneyActivity.class);
        thecontext.startActivity(intent);
    }
    public void renderVerify(){
        Intent intent = new Intent();
        intent.setClass(thecontext, VerifyActivity.class);
        thecontext.startActivity(intent);
    }


}
